<?php
class Tag extends Tut_Model {

    public $id;
    public $name;
    public $slug;
    public $description;
    public $created_date;
    public $last_update;
    public $is_deleted;
    
    private $_asort;
    private $_aSearch;
    private $_areal_sort;
    
    const LIMIT = 10;
    const SORT_SESSION_NAME = 'tag_sort';

    public function __construct($properties = null) {
        parent::__construct($properties);
        $this->_load();
    }
    
    public function save() {
        $this->_prepare_save();
        $asave = array(
            'name' => $this->name,
            'slug' => $this->slug,
            'description' => $this->description,
            'created_date' => $this->created_date,
            'last_update'   => $this->last_update,
            'is_deleted'    => $this->is_deleted
        );
        
        if (empty($this->id)) {
            if ((bool) $this->db->insert('tag', $asave)) {
                return $asave;
            }
            return false;
        }
        
        if ((bool) $this->db->update('tag', $asave, array('id' => $this->id))) {
            return $asave;
        }
    }
    
    private function _prepare_save() {
        //Render string for slug.
        $this->create_slug();
        
        if(!$this->id){
            $this->created_date = time();
        }
        
        $this->last_update = time();
        $this->is_deleted  = 0;
        return $this;
    }
    
    public function create_slug($sname = ''){
        if($sname){
            $this->name = $sname;
            $this->slug = '';
        }
        
        if($this->slug){
            return $this->slug;
        }
        
        $this->slug = preg_replace(array('/\s+/', '/[^a-z0-9-]/'), array('-', ''), $this->name);
        $this->slug = trim($this->slug, '-');
        
        //If get empty.
        if(!$this->slug){
            $ilast_id = $this->get_max_id('tag');
//            var_dump($ilast_id);
            $this->slug = $ilast_id + 1;
            return $this->slug;
        }
        
        //Check if slug is existed.
        if($this->exist('tag', array('slug' => $this->slug))){
//            $atemp = explode('-', $this->slug);
//            
//            if(!is_int($atemp[count($atemp) - 1])){
//                $this->slug =  $this->slug . '-1';
//                return;
//            }
            
            $this->slug = $this->slug . '-' . ($this->get_max_id('tag') + 1);
        }
        
        return $this->slug;
    }

    public function delete($aIds) {
        if (empty($aIds)) {
            return false;
        }
        
        $this->db->where_in('id', array_values($aIds));
        $this->db->update('tag', array('is_deleted' => 1));

        if ($this->db->affected_rows() > 0) {
            return true;
        }

        return false;
    }
    
    public function delete_by_product_id($iproduct_id){
        if (empty($iproduct_id)) {
            return false;
        }
        
        $this->db->delete('tag_product', array('product_id' => $iproduct_id));

        if ($this->db->affected_rows() > 0) {
            return true;
        }

        return true;
    }
    
    public function get_ids_by_name($atag, $iid_product){
        if(!$atag){
            return array();
        }
        
        $otag = $this->db->select('id')->from('tag')->where_in('name', $atag)->get();
        if($otag->num_rows() > 0){
            foreach($otag->result() as $tag) {
                $atag_id[] = array('tag_id' => $tag->id, 'product_id' => $iid_product, 'created_date' => time());
            }
            
            return $atag_id;
        }
        
        return array();
    }

    public function get_by_id($iid = 0) {
        if (empty($iid)) {
            return false;
        }

        $this->db->select('*')->from('tag as t')->where('t.id', $iid);

        $obj = $this->db->get();

        if ($obj->num_rows() > 0) {
            $obj = $obj->row();

            return $obj;
        }

        return false;
    }
    
    public function getByCategoryId($iCategoryId, $bIsCheckActive = false){
        if (empty($iCategoryId)) {
            return false;
        }

        $this->db->select('*')
                ->from('product')
                ->where(array('product_category_id' => $iCategoryId, 'is_deleted' => 0));

        if ($bIsCheckActive) {
            $this->db->where('is_actived', ACTIVE);
        }

        $category = $this->db->get();

        if ($category->num_rows() > 0) {
            $oCategory = $category->result();
            $aCategory = array();
            foreach($oCategory as $value){
                $aCategory[] = $value;
            }
            
            return $aCategory;
        }

        return false;
    }

    private function _prepareArr(array $aArr = null, $isEdit = false) {
        if (empty($aArr)) {
            return false;
        }

        //Unset id to empty.
        if (!$isEdit) {
            unset($aArr['id']);
        }
        //Unset current page.
        unset($aArr['cur_page']);
        //Unset token...
        unset($aArr[$this->config->item('csrf_token_name')]);
        //$aArr['product_category_id'] = $aArr['category'];
        $aArr['product_category_id'] = 1;
        unset($aArr['category']);
        $aArr['language_id'] = $aArr['language'];
        unset($aArr['language']);
        $aArr['level_id'] = $aArr['level'];
        unset($aArr['level']);
        $aArr['date'] = time();
        $aArr['last_update'] = time();
        return $aArr;
    }

    public function gets($skeyword = null, $ilimit = 0) {
        $this->db->select('t.name')
                ->from('tag t');
        
        if($skeyword){
            $oGet = $this->db->like(array('t.name' => $skeyword));
        }
        
        $oGet = $this->db->limit($ilimit ? self::LIMIT : $ilimit)
                        ->order_by('name', 'asc')
                        ->get();
        
        $aGet = array();
        
        if ($oGet->num_rows() > 0) {
            foreach ($oGet->result() as $getObj) {
                $aGet[] = $getObj->name;
            }
        }
        
        return $aGet;
    }

    public function get_list_admin($ioffset, $asearch = null) {
        $this->db->select('SQL_CALC_FOUND_ROWS t.id, t.name, t.slug, t.description, 4 as number_post', false)
                ->from('tag t')
//                ->join('tag_product tp', 'tp.tag_id = t.id')
//                ->join('product p', 'p.id = tp.product_id')
                ->where('t.is_deleted', 0);

        $asearch = $this->prepare_search($asearch);

        foreach ($asearch as $key => $val) {
            if (trim($val) == '') {
                continue;
            }

            switch ($key) {
                case 't.slug':
                case 't.name':
                case 't.description':
                    $this->db->like($key, $val);
                    break;
                default :
                    $this->db->where($key, $val);
                    break;
            }
        }

        /////////////////
        $ilimit = $this->session->userdata(self::ELE_PER_PAGE_ADMIN_SESNAME);

        if (!$ilimit) {
            $ilimit = self::ELE_PER_PAGE_ADMIN;
        }

        $this->db->limit($ilimit, ($ioffset - 1) * $ilimit);

        foreach ($this->_asort as $key => $value) {
            $this->db->order_by($this->_areal_sort[$key], $value);
        }

        $otag = $this->db->get();
        $atag = array();

        if ($otag->num_rows() > 0) {
            foreach ($otag->result() as $obj) {
                $atag[] = $obj;
            }
        }

        $this->_itotal_rows = $this->db->query('SELECT FOUND_ROWS() AS count', false)->row()->count;

        return $atag;
    }
    
    public function get_by_product_id($iid_product){
        if(!$iid_product){
            show_error('Id product is empty');
            return false;
        }
        
        $otag = $this->db->select('t.*, tp.product_id, tp.created_date')
                 ->from('tag as t')
                 ->join('tag_product as tp', 't.id = tp.tag_id')
                 ->where('tp.product_id', $iid_product)
                 ->get();

        if ($otag->num_rows() > 0) {
            foreach ($otag->result() as $obj) {
                $atag[] = $obj;
            }
            return $atag;
        }
        
        return false;
    }

    public function prepare_search($asearch = null) {
        if (empty($asearch)) {
            return array();
        }
        //Prepare search.
        $areturn = array(
            't.name' => $asearch['name'],
            't.slug' => $asearch['slug'],
            't.description' => $asearch['description'],
            'number_post >=' => $asearch['number_post']['from'],
            'number_post <=' => $asearch['number_post']['to'],
            't.id >=' => $asearch['id']['from'],
            't.id <=' => $asearch['id']['to']
        );

        if (!$areturn['number_post >=']) {
            unset($areturn['number_post >=']);
        }

        if (!$areturn['number_post <=']) {
            unset($areturn['number_post <=']);
        }
        
        if (!$areturn['t.id >=']) {
            unset($areturn['t.id >=']);
        }

        if (!$areturn['t.id <=']) {
            unset($areturn['t.id <=']);
        }

        return $areturn;
    }

    public function sort($scol = '') {
        if (empty($scol)) {
            return false;
        }

        $stype_sort = $this->prepare_sort($scol);

        if (!$stype_sort) {
            $this->session->unset_userdata(self::SORT_SESSION_NAME);
        } else {
            $this->session->set_userdata(self::SORT_SESSION_NAME, $this->_asort);
        }

        return $stype_sort;
    }

    public function prepare_sort($scol) {
        if (empty($scol)) {
            return false;
        }

        if (empty($this->_asort[$scol])) {
            $this->_asort = array($scol => 'desc');

            return 'desc';
        } else {
            $stype_sort = $this->_asort[$scol] == 'desc' ? 'asc' : null;

            if (!$stype_sort) {
                unset($this->_asort[$scol]);
            } else {
                $this->_asort[$scol] = $stype_sort;
            }

            return $stype_sort;
        }

        return false;
    }

    public function get_sort() {
        $this->_asort = $this->session->userdata(self::SORT_SESSION_NAME);

        if (!(bool) $this->_asort) {
            return array('name' => 'desc');
        }

        return $this->_asort;
    }
    
    public function get_rule($iid = false, $bis_check_slug = false) {
        $sunique_id = empty($iid) ? '' : "-{$iid}";
        $arule = array(
            array(
                'field' => 'tag[name]',
                'label' => $this->lang->line("pharse var='tag.name'"),
                'rules' => "trim|required|is_unique[tag.name{$sunique_id}]"
            ),
            array(
                'field' => 'tag[description]',
                'label' => $this->lang->line("pharse var='tag.description'"),
                'rules' => "trim"
            )
        );
        
        if($bis_check_slug){
            $arule = array_merge($arule, array(array(
                'field' => 'tag[slug]',
                'label' => $this->lang->line("pharse var='tag.slug'"),
                'rules' => "trim|alpha_dash|is_unique[tag.slug{$sunique_id}]"
            )));
        }
        
        return $arule;
    }
    
    public function get_validation_error() {
        $afield = array('name', 'slug', 'description');
        $avalidation_error = array();
        
        foreach ($afield as $field) {
            $avalidation_error = array_merge($avalidation_error, array("{$field}" => form_error("tag[{$field}]")));
        }

        return $avalidation_error;
    }

    private function _load() {
        $this->_asort = $this->get_sort();
        $this->_areal_sort = array('name' => 't.name', 'number_post' => 'number_post','slug' => 't.slug','description' => 't.description','id' => 't.id');
    }
}

?>